// pages/me/myWallet/myWallet.js
import util from '../../../utils/utils'
import {
  formatTimeDate
} from '../../../utils/formatData';
import {
  CouponHttp
} from '../../../api/coupon.js'
const couponHttp = new CouponHttp();
const app = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    couponInfo: [], //优惠券信息
    couponUsable: [],
    couponAlreadyUsed: [],
    couponTimeOut: [],
    page: 1,
    coponStatus:0,
  },
  initPage() {
    this.httpGetCoupon();
  },
  //点击顶部tab栏
  onTabClick(e) {
    this.setData({
      page: 1,
      couponInfo: []
    })
    this.setData({
      coponStatus: e.detail.name
    })
    console.log(e.detail.name)
    this.httpGetCoupon();
  },

  //获取优惠券信息
  httpGetCoupon() {
    const {
      page,
      couponInfo
    } = this.data
    wx.stopPullDownRefresh();
    return couponHttp.getMyCoupon({
      "page": this.data.page,
      "page_size": 10,
      "coupon_status": this.data.coponStatus
    }).then((res) => {
      let info = page === 1 ? res.coupon_list : couponInfo.concat(res.coupon_list)
      this.judgeStatus(info)
    })
  },
  //判断优惠券类型并对应赋值
  judgeStatus(res) {
    let i = 0;
    let couponUsable = [];
    let couponAlreadyUsed = [];
    let couponTimeOut = [];
    for (i; i < res.length; i++) {
      //格式化时间
      res[i]['effective_time'] = formatTimeDate(new Date(res[i]['start_time'].replace(/\.|\-/g, '/')), 'yyyy-MM-dd') + "-" + formatTimeDate(new Date(res[i]['end_time'].replace(/\.|\-/g, '/')), 'yyyy-MM-dd')
      if (res[i].coupon_status === 1) {
        couponUsable.push(res[i])
      }
      if (res[i].coupon_status === 2) {
        couponAlreadyUsed.push(res[i])
      }
      if (res[i].coupon_status === 4) {
        couponTimeOut.push(res[i])
      }
    }
    this.setData({
      couponInfo: res,
      couponUsable: couponUsable,
      couponAlreadyUsed: couponAlreadyUsed,
      couponTimeOut: couponTimeOut,
    });
  },


  //下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      page: 1
    })
    this.httpGetCoupon();
  },

  // 页面上拉触底事件的处理函数
  onReachBottom: function() {
    this.setData({
      page: this.data.page + 1
    })
    this.httpGetCoupon()
  }
});